const Notification = require('../models/Notification');
const User = require('../models/User');

// 创建通知
exports.createNotification = async ({
  recipient,
  sender,
  type,
  targetType,
  targetId,
  targetModel,
  commentId,
  content
}) => {
  try {
    return await Notification.create({
      recipient,
      sender,
      type,
      targetType,
      targetId,
      targetModel,
      commentId,
      content
    });
  } catch (error) {
    console.error('创建通知失败:', error);
    throw error;
  }
};

// 获取用户的通知列表
exports.getNotifications = async (req, res) => {
  try {
    const notifications = await Notification.find({ recipient: req.user._id })
      .populate('sender', 'username avatar')
      .sort('-createdAt');

    res.json({
      code: 200,
      data: notifications,
      message: '获取通知成功'
    });
  } catch (error) {
    console.error('获取通知失败:', error);
    res.status(500).json({ message: '获取通知失败，请稍后重试' });
  }
};

// 标记通知为已读
exports.markAsRead = async (req, res) => {
  try {
    const { notificationId } = req.params;
    
    await Notification.findByIdAndUpdate(notificationId, { isRead: true });
    
    res.json({
      code: 200,
      message: '标记已读成功'
    });
  } catch (error) {
    console.error('标记通知已读失败:', error);
    res.status(500).json({ message: '操作失败，请稍后重试' });
  }
};

// 标记所有通知为已读
exports.markAllAsRead = async (req, res) => {
  try {
    await Notification.updateMany(
      { recipient: req.user._id, isRead: false },
      { isRead: true }
    );
    
    res.json({
      code: 200,
      message: '全部标记已读成功'
    });
  } catch (error) {
    console.error('标记所有通知已读失败:', error);
    res.status(500).json({ message: '操作失败，请稍后重试' });
  }
};

// 删除通知
exports.deleteNotification = async (req, res) => {
  try {
    const { notificationId } = req.params;
    
    await Notification.findByIdAndDelete(notificationId);
    
    res.json({
      code: 200,
      message: '删除通知成功'
    });
  } catch (error) {
    console.error('删除通知失败:', error);
    res.status(500).json({ message: '删除失败，请稍后重试' });
  }
};

// 获取未读通知数量
exports.getUnreadCount = async (req, res) => {
  try {
    const count = await Notification.countDocuments({
      recipient: req.user._id,
      isRead: false
    });
    
    res.json({
      code: 200,
      data: count,
      message: '获取未读通知数量成功'
    });
  } catch (error) {
    console.error('获取未读通知数量失败:', error);
    res.status(500).json({ message: '获取数量失败，请稍后重试' });
  }
};
